package com.example.yt_app.Othre;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.example.yt_app.Interface.SB_HttpBinService;
import com.example.yt_app.R;
import com.example.yt_app.Interface.HttpbinService;
import com.example.yt_app.Urils.Json;
import com.example.yt_app.Urils.State;
import com.example.yt_app.Urils.Utils;
import com.example.yt_app.bean.HistoricalData.Data;
import com.example.yt_app.bean.HistoricalData.Datapoints;
import com.example.yt_app.bean.HistoricalData.Datastreams;
import com.example.yt_app.bean.HistoricalData.HistoricalJsonRootBean;

import com.example.yt_app.bean.Onenet.JsonRootBean;
import com.example.yt_app.bean.Onenet_online.Devices;
import com.example.yt_app.bean.Onenet_online.Online_json;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;


import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by dell on 2021/7/11.
 */
@SuppressWarnings("ALL")
public class Okhttp extends AppCompatActivity {
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.button1)
    Button button1;
    @BindView(R.id.button2)
    Button button2;
    @BindView(R.id.button3)
    Button button3;

    private static final String TAG = "OKhttp";
    private OkHttpClient okHttpClient;
    private Retrofit retrofit;
    private HttpbinService httpbinService;
    static String time;//时间
    static String wendu;//温度
    static String shidu;//湿度
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.okhttp);
        //绑定处理
        ButterKnife.bind(this);
        okHttpClient = new OkHttpClient();
        retrofit =  new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
        httpbinService = retrofit.create(HttpbinService.class);

    }
    @SuppressWarnings("AlibabaConstantFieldShouldBeUpperCase")
    private static final String DeviceID = "736585581";
    @SuppressWarnings("AlibabaConstantFieldShouldBeUpperCase")
    private static final String DeviceIDs = "735471469,735480350,735480495,736585581";


    @SuppressWarnings("AlibabaConstantFieldShouldBeUpperCase")
    private static final String inmange = "temp,humi";
    private String responseData;
    @OnClick(R.id.button)
    public void getSync(View view){
        Request request = new Request.Builder()
                .url("http://api.heclouds.com/devices/status?" +"devIds="+ DeviceIDs )
                .header("api-key", com.example.yt_app.Urils.State.ApiKey).build();
        Call call =okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {


                    /*response.body().string()中的 (.string)只能使用一次*/
                    //Log.i(TAG , "postAsync" + response.body().string());
                    responseData = response.body().string();
                    Log.i(TAG , "postAsync" + responseData);
                    Online_json online = Json.gson.fromJson(responseData, Online_json.class);
                    Log.i(TAG , online.getData().toString());
                    int i =online.getData().getTotal_count();
                    List<Devices> devices = online.getData().getDevices();
                    Log.i(TAG , devices.toString());
                    for (i = 0 ;i<online.getData().getTotal_count();i++){

                        System.out.println("\n设备名"+devices.get(i).getTitle()
                                +"是否在线"+devices.get(i).getOnline());
                    }

//                    System.out.println(devices.get(2).getId());
//                    System.out.println(devices.get(2).getOnline());
//                    List<Devices> title1 = data.get(1).getDevices();
//                    System.out.println(title1);
//                    List<Devices> title2 = data.get(2).getDevices();
//                    System.out.println(title2);
                   // JsonRootBean app = Json.gson.fromJson(responseData, JsonRootBean.class);
                    //List<Data> streams = app.getData();
//                    List<Data> streams = (List<Data>) app.getData();
//                    shidu = streams.get(1).getCurrent_value();
//                    Log.i(TAG , "postAsync" + shidu);
//                    Log.w("www","wendu="+wendu);//log输出
                } catch (IOException e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

        });
//        new Thread(){
//            public void run(){
//
//                try {
//                    Response response = call.execute();
//                    String responseData = response.body().string();
//
//                    Online_json online = Json.gson.fromJson(responseData, Online_json.class);
//                    List<com.example.yt_app.bean.Onenet_online.Data> data = (List<com.example.yt_app.bean.Onenet_online.Data>) online.getData();
//                    List<Devices> title1 = data.get(1).getDevices();
//                    System.out.println(title1);
//                    List<Devices> title2 = data.get(2).getDevices();
//                    System.out.println(title2);
//                    //List<Devices> devices = data.getDevices();
//                }catch (IOException e){
//                    e.printStackTrace();
//                }
//            }
//        }.start();
    }
    /*端口链接*/

//    Retrofit YT_retrofit_2 =  new Retrofit
//            .Builder()
//            .addConverterFactory(GsonConverterFactory.create())//添加转换器
//            .baseUrl("http://api.heclouds.com/devices/" + DeviceID + "/datapoints")
//            .build();
//    YT_HttpBinService yt_httpBinService_2 = YT_retrofit_2.create(SB_HttpBinService.class);
    //@OnClick(R.id.button1)
//    public void getAsync(View view){
//        Request request = new Request.Builder()
//                .url("http://api.heclouds.com/devices/" + DeviceID + "/datastreams/" )
//                .header("api-key", State.ApiKey).build();
//        Call call =okHttpClient.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//                try {
//                    /*response.body().string()中的 (.string)只能使用一次*/
//                    //Log.i(TAG , "postAsync" + response.body().string());
//                    responseData = response.body().string();
//                    JsonRootBean app = Json.gson.fromJson(responseData, JsonRootBean.class);
//                    List<Data> streams = (List<Data>) app.getData();
//                    System.out.println(streams.get(0).getUnit_symbol());
//                    wendu = streams.get(0).getCurrent_value()+streams.get(0).getUnit_symbol();
//                    shidu = streams.get(1).getCurrent_value()+streams.get(1).getUnit_symbol();
//                    Log.i(TAG , "postAsync" + shidu);
//                    Log.w("www","wendu="+wendu);//log输出
//                } catch (IOException e){
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(@NotNull Call call, @NotNull IOException e) {
//
//            }
//
//            });
//
//        }
//
//


    //@OnClick(R.id.button2)
//    public void postSync(View view){
//        new Thread(){
//            @Override
//            public void run() {
//                FormBody formBody = new FormBody.Builder()
//                        .add("a","1").add("b","2").build();
//                Request request = new Request.Builder().url("https://www.httpbin.org/post")
//                        .post(formBody).build();
//                Call call =okHttpClient.newCall(request);
//                try {
//
//                    Response response = call.execute();
//                    Log.i(TAG ,"PostSync" + response.body().string());
//                    String responseData = response.body().string();
//                    //json提取数据
//                    JsonRootBean app = Json.gson.fromJson(responseData, JsonRootBean.class);
//                    List<Data> streams = app.getData();
//
//
//                    shidu = streams.get(1).getCurrent_value();
//                    Log.w("www","wendu="+wendu);//log输出
//
//                }catch (IOException e){
//                    e.printStackTrace();
//                }
//            }
//        }.start();
//
//    }
    /**
     *  RX
     * */
    @OnClick(R.id.button3)
    public void dd(){
        Request request = new Request.Builder()
                .url("http://api.heclouds.com/devices/735471469/datapoints?"
                        +"start="+"2021-07-28T08:00:35"+"&"
                        +"end="+"2021-07-30T08:00:35")
                .header("api-key", State.ApiKey).build();
        Call call =okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    /*response.body().string()中的 (.string)只能使用一次*/
                    //Log.i(TAG , "postAsync" + response.body().string());
                    String responseData = response.body().string();
                    Log.i(TAG , "postAsync" + responseData);
                    HistoricalJsonRootBean historicalJsonRootBean = Json.gson.fromJson(responseData, HistoricalJsonRootBean.class);

                    List<Datastreams> data = (List<Datastreams>) historicalJsonRootBean.getData().getDatastreams();
                    List<Datapoints> datapoints = (List<Datapoints>) data.get(0).getDatapoints();
                    System.out.println(historicalJsonRootBean.getData().getCount());
                    //System.out.println(data.get(0).getDatapoints().get(0).getValue());

                    for (int i = 0; i < historicalJsonRootBean.getData().getCount(); i++){
                        System.out.println(datapoints.get(i).getValue());
                        String update_t = Utils.dateToString(datapoints.get(i).getAt(),"yyyy-MM-dd HH:mm:ss");
                        System.out.println(update_t);
                    }
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }

        });

    }

    /**
     *  RX
     * */
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @OnClick(R.id.button2)
    public void RxAsync(){

        //步骤4：创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.heclouds.com/devices/735471469/datapoints") // 设置 网络请求 Url
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        // 步骤5：创建 网络请求接口 的实例
        SB_HttpBinService request = retrofit.create(SB_HttpBinService.class);
        // 步骤6：采用Observable<...>形式 对 网络请求 进行封装
        Observable<HistoricalJsonRootBean> observable = request.getSbMessage(State.ApiKey,"2021-07-30T08:00:35","2021-07-28T08:00:35");
        // 步骤7：发送网络请求
        observable.subscribeOn(Schedulers.io())               // 在IO线程进行网络请求
                .observeOn(AndroidSchedulers.mainThread())  // 回到主线程 处理请求结果
                .subscribe(new Observer<HistoricalJsonRootBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d("TAG", "开始采用subscribe连接");
                    }

                    @Override
                    public void onNext(@NotNull HistoricalJsonRootBean historicalJsonRootBean) {
                        Log.i("gg",historicalJsonRootBean.toString());
                        //List<Devices> devices = historicalJsonRootBean.getData().getDevices();

                    }


                    @Override
                    public void onError(Throwable e) {
                        Log.d("TAG," ,"请求失败");
                    }

                    @Override
                    public void onComplete() {
                        Log.d("TAG", "请求成功");
                    }
                });
    }
    @SuppressWarnings("AlibabaRemoveCommentedCode")
    public void postAsync(View view){
//        FormBody formBody = new FormBody.Builder()
//                .add("a","1").add("b","2").build();
//        Request request = new Request.Builder().url("https://www.httpbin.org/post")
//                .post(formBody).build();
//        Call call =okHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(@NotNull Call call, @NotNull IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//                Log.i(TAG ,"PostAsync" + response.body().string());
//            }
//        });

        retrofit2.Call<ResponseBody> call = httpbinService.post("lance", "123");

        call.enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {

                try {
                    Log.i(TAG , "postAsync" + response.body().string());

                } catch (IOException e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

            }
        });

    }
    /**
     * 拦截器
     * */

    @SuppressWarnings("AlibabaAvoidManuallyCreateThread")
    public void interceptorTest(){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public Response intercept(@NotNull Chain chain) throws IOException {
                       //前置处理
                       Request request = chain.request().newBuilder()
                                .addHeader("os","android")
                                .addHeader("version","1.0").build();
                       //后置处理
                       Response response = chain.proceed(request);
                       return response;
                    }
                }).addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public Response intercept(@NotNull Chain chain) throws IOException {
                        System.out.println("version" + chain.request().header("version"));
                        return chain.proceed(chain.request());
                    }
                }).build();
        //noinspection AlibabaAvoidManuallyCreateThread
        new Thread(){
            @Override
            public void run() {
                FormBody formBody = new FormBody.Builder()
                        .add("a","1").add("b","2").build();
                Request request = new Request.Builder().url("https://www.httpbin.org/post")
                        .post(formBody).build();
                Call call =okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    Log.i(TAG ,"PostSync" + response.body().string());
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }.start();
    }

}
